package com.zhiwang.planet.ui.jsmodule

import android.content.ContentValues
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.webkit.JavascriptInterface
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.afollestad.materialdialogs.MaterialDialog
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.google.android.material.snackbar.Snackbar
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.liulishuo.filedownloader.util.FileDownloadUtils
import com.planet.processor.JsModule
import com.tencent.bugly.crashreport.BuglyLog
import com.tencent.bugly.crashreport.CrashReport
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerUserComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.mvp.p.UserPresenter
import com.zhiwang.planet.ui.BaseActivity
import com.zhiwang.planet.ui.loginv2.LoginV2Activity
import com.zhiwang.planet.util.*
import kotlinx.android.synthetic.main.invite_dialog_layout.view.*
import java.io.File
import javax.inject.Inject


@JsModule
class ShareModule constructor(context: BaseActivity) : BaseJsModule(context) {


    @Inject
    lateinit var userPresenter: UserPresenter


    init {

        DaggerUserComponent.builder()
                .appComponent(context.getAppComponent())
                .autoDisposeModule(AutoDisposeModule(context))
                .accountModule(AccountModule(context))
                .build()
                .inject(this)


    }
    /*分享*/

    /**
     * js h5 点击分享，回调使用 原生的分享功能
     */
    @JavascriptInterface
    fun share() {
        context.runOnUiThread {
            showShareDialog("")
        }
    }


    @JavascriptInterface
    fun share(url: String) {
        showShareDialog(url)
    }

    private fun showShareDialog(qrUrl: String) {

        if (TextUtils.isEmpty(qrUrl)) {
            Toaster.message("二维码地址为空")
            return;
        }

        val rootView = context.layoutInflater.inflate(R.layout.invite_dialog_layout, null)
        val shareDialog = AlertDialog.Builder(this)
                .setView(rootView)
                .create()
        rootView.findViewById<View>(R.id.closeBtn).setOnClickListener { shareDialog.dismiss() }
        val shareInfo = userPresenter.getShareInfo()
        rootView.findViewById<View>(R.id.share_wechat).setOnClickListener {
            downloadSharePicAndStartShare(shareInfo.img) {
                ShareHelper.create(this).shareImgeToWxFriend(shareInfo)
                shareDialog.dismiss()
            }
        }
        rootView.findViewById<View>(R.id.share_timeline).setOnClickListener {
            downloadSharePicAndStartShare(shareInfo.img) {
                ShareHelper.create(this).shareImgeToWxTimeLine(shareInfo)
                shareDialog.dismiss()
            }

        }
        rootView.findViewById<View>(R.id.share_qq).setOnClickListener {
            ShareHelper.create(this).shareImageToQQFriend(context, shareInfo.imgLocalPath!!, shareInfo.url)
            shareDialog.dismiss()
        }
        rootView.findViewById<View>(R.id.share_SB).setOnClickListener {
            downloadSharePicAndStartShare(shareInfo.img) {
                ShareUtil.shareToWeibo(this, shareInfo)
                shareDialog.dismiss()
            }
        }
        rootView.findViewById<View>(R.id.share_qqzone).setOnClickListener {
            ShareHelper.create(this).shareImageToQQZone(context, shareInfo.imgLocalPath!!, shareInfo.url)
            shareDialog.dismiss()
        }


        rootView.share_qrcode.setOnClickListener {

            val userId = TokenManager.webviewHeaderUserid()

            if (TextUtils.isEmpty(userId)) {
                TokenManager.clearToken()
                context.onAuthExpired()
            }

            val imageView = ImageView(this)

            val frameLayout = FrameLayout(this)

            frameLayout.minimumHeight = 150.dp
            frameLayout.setBackgroundResource(R.color.white)
            imageView.adjustViewBounds = true
            imageView.scaleType = ImageView.ScaleType.FIT_XY

            val lp = FrameLayout.LayoutParams(150.dp, 150.dp)
            lp.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM
            lp.topMargin = 20.dp
            frameLayout.addView(imageView, lp)

            frameLayout.addView(TextView(this).apply { text = "id:$userId" },
                    FrameLayout.LayoutParams(-2, -2)
                            .also {
                                it.gravity = Gravity.CENTER_HORIZONTAL
                            })

            Glide.with(this)
                    .load(qrUrl/*BuildConfig.BASE_URL + "invite/app_share?uid=$userId"*/)
                    .listener(object : RequestListener<Drawable> {
                        override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                            shareDialog.dismiss()
                            return false
                        }

                        override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                            return false
                        }

                    })
                    .into(imageView)

            MaterialDialog.Builder(this)
                    .backgroundColorRes(R.color.white)
                    .title("邀请好友")
                    .customView(frameLayout, false)
                    .build()
                    .show()
        }

        shareDialog.show()
    }

    fun saveLocal(v: View) {

        FileDownloader.getImpl()
                .create(BuildConfig.BASE_URL + "invite/app_share?uid=${TokenManager.webviewHeaderUserid()}")
                .setPath(
                        File(
                                getExternalFilesDir(Environment.DIRECTORY_PICTURES),
                                FileDownloadUtils.generateFileName(BuildConfig.BASE_URL + "invite/app_share?uid=${TokenManager.webviewHeaderUserid()}")
                        ).absolutePath,
                        false)
                .setListener(object : FileDownloadListener() {
                    override fun warn(task: BaseDownloadTask?) {

                    }

                    override fun completed(task: BaseDownloadTask?) {

                        val f = File(task?.path)
                        if (f.exists()) {
                            writeImageFile(f)
                        }
                    }

                    override fun pending(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                    }

                    override fun error(task: BaseDownloadTask?, e: Throwable?) {

                    }

                    override fun progress(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                    }

                    override fun paused(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                    }

                })
                .start()


    }

    fun writeImageFile(file: File) {
        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, System.currentTimeMillis().toString())
            put(MediaStore.MediaColumns.MIME_TYPE, "image/*")
            if (Build.VERSION.SDK_INT >= 29) {
                put("relative_path", file.path)
                put("is_pending", 1)
            }
        }

        val uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)

        try {
            uri?.let {
                contentResolver.openOutputStream(it)?.apply {
                    write(file.readBytes())
                    close()
                }

            }

            Snackbar.make(context.findViewById(android.R.id.content), "保存成功", Snackbar.LENGTH_LONG)
                    .setAction("查看") {
                        val fileUri = uri

                        val starter = Intent(Intent.ACTION_VIEW)
                        starter.putExtra(Intent.EXTRA_STREAM, fileUri)
                        starter.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                                or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                                or Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        starter.setDataAndType(fileUri, "image/*")
                        startActivity(starter)
                    }.show()
        } catch (e: Exception) {

        }

    }

    private fun downloadSharePicAndStartShare(url: String, function: () -> Unit) {
        val file = File(Environment.getExternalStorageDirectory(), "planetSharePic")

        if (file.exists() && file.length() != 0L) {
            //share
            function.invoke()
        } else {

            FileDownloader.getImpl().create(url)
                    .setPath(file.absolutePath)
                    .setForceReDownload(false)
                    .setListener(object : FileDownloadListener() {
                        override fun warn(task: BaseDownloadTask?) {

                        }

                        override fun completed(task: BaseDownloadTask?) {
                            function.invoke()
                        }

                        override fun pending(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                        }

                        override fun error(task: BaseDownloadTask?, e: Throwable?) {
                            BuglyLog.e("保存分享图片失败", e?.message)
                            CrashReport.postCatchedException(Throwable("保存分享图片失败:" + e?.message))
                        }

                        override fun progress(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                        }

                        override fun paused(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                        }

                    })
                    .start()
        }


    }
}